from waveapi import events
from waveapi import model
from waveapi import robot
from dieroll_std import std
from dieroll_utils import roller_manager

helpstring = (
    "Hi! I am an RPG game assistant. I am here to help you. These "
    "are my main options:"
    "  roll [expression]: roll dice based on the expression given")

def OnRobotAdded(properties, context):
  """Invoked when the robot has been added."""
  root_wavelet = context.GetRootWavelet()
  root_wavelet.CreateBlip().GetDocument().SetText(
      "Hi! I am your RPG assistant.")

def OnBlipSubmitted(properties, context):
  """Message sent. Parse it."""
  blip = context.GetBlipById(properties["blipId"])
  input_text = blip.GetDocument().GetText().strip().split()
  if input_text[0] == 'help' and len(input_text) == 1:
    blip.CreateChild().GetDocument().SetText(helpstring)
  if input_text[0] == 'roll':
    dice_expression = ' '.join(input_text[1:])
    try:
      manager = roller_manager()
      manager.setRoller(std)
      result = manager.processRoll(dice_expression)
    except:
      result = "Error parsing expression: %s" % (dice_expression)

    blip.CreateChild().GetDocument().SetText(result)


if __name__ == '__main__':
  myRobot = robot.Robot('RPG helper',
      image_url='http://obirpg.appspot.com/images/dice.jpg',
      version='1-0-alpha2',
      profile_url='http://obirpg.appspot.com/')
  myRobot.RegisterHandler(events.WAVELET_SELF_ADDED, OnRobotAdded)
  myRobot.RegisterHandler(events.BLIP_SUBMITTED, OnBlipSubmitted)
  myRobot.Run()
